package com.kalix.vote.management.biz;

import com.kalix.framework.core.api.persistence.JsonData;
import com.kalix.framework.core.api.persistence.JsonStatus;
import com.kalix.framework.core.impl.biz.ShiroGenericBizServiceImpl;
import com.kalix.vote.management.api.biz.*;
import com.kalix.vote.management.api.dao.IVoteBeanDao;
import com.kalix.vote.management.entities.*;

import javax.transaction.Transactional;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

public class VoteBeanServiceImpl extends ShiroGenericBizServiceImpl<IVoteBeanDao, VoteBean> implements IVoteBeanService {
    private IVoteConfigBeanService voteConfigBeanService;
    private ICourseBeanService courseBeanService;
    private ITeacherBeanService teacherBeanService;
    private ITeamCadreBeanService teamCadreBeanService;

    public void setVoteConfigBeanService(IVoteConfigBeanService voteConfigBeanService) {
        this.voteConfigBeanService = voteConfigBeanService;
    }

    public void setCourseBeanService(ICourseBeanService courseBeanService) {
        this.courseBeanService = courseBeanService;
    }

    public void setTeacherBeanService(ITeacherBeanService teacherBeanService) {
        this.teacherBeanService = teacherBeanService;
    }

    public void setTeamCadreBeanService(ITeamCadreBeanService teamCadreBeanService) {
        this.teamCadreBeanService = teamCadreBeanService;
    }


    @Override
    public JsonData getVoteCourseInfos(String showType) {
        List<CourseBean> courseBeanList = courseBeanService.getAllCourseInfo();
        VoteConfigBean voteConfig = voteConfigBeanService.getVoteConfigByType("1");
        if ("1".equals(showType)) {
            // 计算总票数
            List<VoteBean> voteList = getVoteByConfig(voteConfig);
            if (voteList != null && !voteList.isEmpty()) {
                final Map<String, Long> map = getVoteMap(voteList);
                if (map != null && courseBeanList != null && !courseBeanList.isEmpty()) {
                    courseBeanList = courseBeanList.parallelStream().map(c->{
                        Long id = c.getId();
                        System.out.println("id====================");
                        System.out.println(id);
                        Long countVal = map.get(String.valueOf(id));
                        if (countVal == null) {
                            countVal = 0L;
                        }
                        c.setVoteCount(countVal.intValue());
                        return c;
                    }).collect(Collectors.toList());
                }
            }
        }
        List<Map<String, Object>> resultList = getResultList(courseBeanList, voteConfig);
        return getResult(resultList);
    }

    private Map<String, Long> getVoteMap(List<VoteBean> voteList) {
        Map<String, Long> map  = voteList.parallelStream().filter(v->v.getContents() != null)
                .map(vo->vo.getContents())
                .map(vs->{
                    if (vs.indexOf(",") == -1) {
                        return new String[]{vs};
                    } else {
                        return vs.split(",");
                    }
                })
                .flatMap(s->Arrays.stream(s))
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
        return map;
    }

    private List<VoteBean> getVoteByConfig(VoteConfigBean voteConfig) {
        return getVoteByConfigAndUserId(voteConfig, null);
    }

    private List<VoteBean> getVoteInfos(String voteType, Long userId) {
        VoteConfigBean voteConfig = voteConfigBeanService.getVoteConfigByType(voteType);
        List<VoteBean> voteInfos = getVoteByConfigAndUserId(voteConfig, userId);
        return voteInfos;
    }

    private List<VoteBean> getVoteByConfigAndUserId(VoteConfigBean voteConfig, Long userId) {
        Date endDate = voteConfig.getEndDate();
        Date startDate = voteConfig.getStartDate();
        String endDateStr = gatFormatDate(endDate);
        String startDateStr = gatFormatDate(startDate);
        String voteType = voteConfig.getVoteType();
        String sql = "select * from vote_info where voteType = '" + voteType + "'"
                + " and endDate=to_timestamp('"+endDateStr+"','YYYY-MM-DD hh24:mi:ss')"
                + " and startDate=to_timestamp('"+startDateStr+"','YYYY-MM-DD hh24:mi:ss')";
        if (userId != null) {
            sql += " and voteUserId = " + userId;
        }
        return dao.findByNativeSql(sql, VoteBean.class);
    }

    private String gatFormatDate(Date date) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return formatter.format(date);
    }

    @Override
    public JsonData getVoteTeacherInfos(String showType) {
        List<TeacherBean> teacherBeanList = teacherBeanService.getAllTeacherInfo();
        VoteConfigBean voteConfig = voteConfigBeanService.getVoteConfigByType("2");
        if ("1".equals(showType)) {
            // 计算总票数
            List<VoteBean> voteList = getVoteByConfig(voteConfig);
            if (voteList != null && !voteList.isEmpty()) {
                final Map<String, Long> map = getVoteMap(voteList);
                if (map != null && teacherBeanList != null && !teacherBeanList.isEmpty()) {
                    teacherBeanList = teacherBeanList.parallelStream().map(c->{
                        Long id = c.getId();
                        Long countVal = map.get(String.valueOf(id));
                        if (countVal == null) {
                            countVal = 0L;
                        }
                        c.setVoteCount(countVal.intValue());
                        return c;
                    }).collect(Collectors.toList());
                }
            }
        }

        List<Map<String, Object>> resultList = getResultList(teacherBeanList, voteConfig);
        return getResult(resultList);
    }

    @Override
    public JsonData getVoteTeamCadreInfos(String showType) {
        List<TeamCadreBean> teamCadreBeanList = teamCadreBeanService.getAllTeamCadreInfo();
        VoteConfigBean voteConfig = voteConfigBeanService.getVoteConfigByType("3");
        if ("1".equals(showType)) {
            // 计算总票数
            List<VoteBean> voteList = getVoteByConfig(voteConfig);
            if (voteList != null && !voteList.isEmpty()) {
                final Map<String, Long> map = getVoteMap(voteList);
                if (map != null && teamCadreBeanList != null && !teamCadreBeanList.isEmpty()) {
                    teamCadreBeanList = teamCadreBeanList.parallelStream().map(c->{
                        Long id = c.getId();
                        Long countVal = map.get(String.valueOf(id));
                        if (countVal == null) {
                            countVal = 0L;
                        }
                        c.setVoteCount(countVal.intValue());
                        return c;
                    }).collect(Collectors.toList());
                }
            }
        }

        List<Map<String, Object>> resultList = getResultList(teamCadreBeanList, voteConfig);
        return getResult(resultList);
    }


    @Override
    @Transactional
    public JsonStatus saveVoteInfo(VoteBean voteBean) {
        if (checkVoted(voteBean)) {
            return JsonStatus.failureResult("您已经投过票！");
        }
        try {
            // 投票记录保存
            dao.save(voteBean);
            return JsonStatus.successResult("投票成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return JsonStatus.failureResult("投票失败！");
        }
    }

    private Boolean checkVoted(VoteBean voteBean) {
        Long userId = voteBean.getVoteUserId();
        String voteType = voteBean.getVoteType();
        List<VoteBean> voteInfos = getVoteInfos(voteType, userId);
        if (voteInfos != null && !voteInfos.isEmpty()) {
            return true;
        }
        return false;
    }

    private List<Map<String, Object>> getResultList(List<?> voteList, VoteConfigBean voteConfig) {
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("voteList", voteList);
        resultMap.put("voteConfig", voteConfig);
        List<Map<String, Object>> resultList = new ArrayList<>();
        resultList.add(resultMap);
        return resultList;
    }

    private JsonData getResult(List<?> list) {
        JsonData jsonData = new JsonData();
        if (list == null) {
            jsonData.setTotalCount(0L);
        } else {
            jsonData.setTotalCount(Long.valueOf(list.size()));
        }
        jsonData.setData(list);
        return jsonData;
    }
}
